package com.alibaba.handler.security;

import com.alibaba.common.ResponseResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.alibaba.define.enums.AppHttpCodeEnum.NO_OPERATOR_AUTH;

/**
 * @author : hanyang
 * @date : 2023-11-04 12:50
 **/

@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        log.error("AccessDeniedHandlerImpl#handle Exception:{}", JSON.toJSONString(e));
        // 响应给前端
        ResponseResult<Object> error = ResponseResult.error(NO_OPERATOR_AUTH.getCode(), NO_OPERATOR_AUTH.getMsg());
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(error));
    }
}
